<?php
namespace App\Http\Controllers\Api;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Models\Order;
use App\Models\Goods;
use App\Models\GoodsSkuStock;
use App\Models\Payment;
// use EasyWeChat\Factory;
// use Ardon\EucpSms\Eucp;
use Log;
// use App\Services\Payment\Sumpay;
use App\Services\Payment\Lianlianpay\Lianlianpay;

class PaymentController extends Controller
{
    /**
     * @api {post} /payment/llpay_notify
     * 支付回调
     */
    public function llpay_notify(Request $request)
    {
        Log::info('payment llpay_notify-------------------------');

        $request = $request->all();
        Log::info('payment llpay_notify request:'. json_encode($request));

        $sign = request()->header('Signature-Data');
        Log::info('payment llpay_notify sign:'. $sign);

        // 线下转账回调
        // $sign = 'Wi8bCiw36nQwCiZ3zGn6BNlmnoO65f7c9rqqowTZojEcgqVbWa3ug3fTnvNyOMGHBCT7D++X/oMX7l0DhuQiO0morf4g23p/dv43PMxIJClnfXAOwPMut+45FW6daaDTozo5wXVYStVNWXEf32dosVhBFAq3Heob4Tn8OIT4ANY=';
        // $request = '{"oid_partner":"402503060000031388","payerInfo":[{"amount":"0.02","method":"BANK_TRANSFER_UNFREEZE","payer_type":"MERCHANT","payer_id":"402503060000031388"}],"txn_type":"GENERAL_CONSUME","accept_details":[{"virtualno":"2527443321493675","payer_acctname":"\u6d6e\u79c0\u51ac","total_amount":"0.02","refund_amount":"0.00","payer_acctno":"6214850216117397","state":"MATCHED","detail_txno":"20250416000080100902","arrival_date":"20250416151140","oth_bank_name":"\u62db\u5546\u94f6\u884c","match_amount":"0.02","pending_amount":"0.00"}],"payeeInfo":[{"amount":"0.02","payee_id":"402503060000031388","payee_type":"MERCHANT"}],"orderInfo":{"total_amount":"0.02","txn_seqno":"20250416153279667","txn_time":"20250416151043","order_info":"{\"order_bn\":\"2025041615327\",\"payment_type\":\"lianlpay_offline\"}"},"offlineTrans":{"virtualno":"2527443321493675"},"txn_status":"TRADE_SUCCESS","accounting_date":"20250416","finish_time":"20250416151431","accp_txno":"2025041616431698"}';
        // $request = json_decode($request);
        // dd($sign, $request);

        // 小程序在线支付回调
        // $sign = 'WxER/5ejogI/YoB2Qtaq5mzctWfMz7b5yk82Db1/ToUPPbPEuPqc/9w5ApUj0FcmjPuYcgGyaGvcw4WUswtthdcFWdEXK8D2BCuNpckreEx84241EHUc31MoukO06LP7ylPzzCps0QS6HMcgmnmsSCzoC3Il/4MwXOgHJBTPVNw=';
        // $request = '{"oid_partner":"402503060000031388","channel_data":"{\"transaction_id\":\"4200002626202504161710226448\",\"out_trade_no\":\"2025041618365258712\",\"bank_type\":\"OTHERS\",\"coupon_fee\":\"0\",\"card_type\":\"OTHER\",\"sub_openid\":\"oivXD674rmRHMWpH7e6pQ7PXj3jk\"}","finish_time":"20250416150941","accp_txno":"2025041616407464","sub_chnl_no":"2025041618365258712","payerInfo":[{"amount":"0.01","method":"WECHAT_APP_WXA","payer_type":"USER","payer_id":"1","chnl_payer_id":"oivXD674rmRHMWpH7e6pQ7PXj3jk"}],"txn_type":"GENERAL_CONSUME","payeeInfo":[{"amount":"0.01","payee_id":"402503060000031388","payee_type":"MERCHANT"}],"orderInfo":{"total_amount":"0.01","txn_seqno":"2025041615418151","txn_time":"20250416150928"},"chnl_txno":"2025041672913422","txn_status":"TRADE_SUCCESS","pay_chnl_txno":"4200002626202504161710226448","accounting_date":"20250416"}';
        // $request = json_decode($request);

        $res = Lianlianpay::checkSign(json_encode($request, JSON_UNESCAPED_UNICODE), $sign);
        Log::info('payment llpay_notify res:'. $res);
        // Log::info('payment llpay_notify res:'. $request['txn_status']);
        // $res = 1;

        // if ($res && isset($request['txn_status']) && $request['txn_status']=='TRADE_SUCCESS')
        if ($res)
        {
            $request = json_decode(json_encode($request, JSON_UNESCAPED_UNICODE), 1);
            // 处理订单信息

            // 更新支付单
            $payment = Payment::where('pay_no', $request['accp_txno'])->whereIn('status', ['ready', 'failed'])->first();

            if ($payment)
            {
                $order_pay = Order::where('order_bn', $payment->order_bn)->where('pay_status', 'paid')->first();
                if ($order_pay)
                {
                    Log::info('payment llpay_notify return: Success  已支付过');
                    echo 'Success';exit;
                }
                else
                {
                    $payment->status = 'success';

                    $payment->pay_return = json_encode($request);

                    // $payment->payment_code = 'lianlianpay';

                    $payment->remark = '支付成功';

                    $payment_res = $payment->save();

                    if ($payment_res)
                    {
                        if (isset($request['payerInfo']))
                        {
                            $amount_arr = array_column($request['payerInfo'], 'amount');
                            $paid_amount = array_sum($amount_arr);
                        }
                        else
                        {
                            $paid_amount = $payment->paid_amount;
                        }

                        // 更新订单
                        $order = Order::where('order_bn', $payment->order_bn)->with('detail')->first();
                        // dd($order->toArray());
                        $order->pay_status = 'paid';

                        $order->paid_amount = $paid_amount;

                        $order->payment_code = $payment->payment_code;

                        $order->payed_time = date('Y-m-d H:i:s');
                        $order->payed_time = date('Y-m-d H:i:s');

                        $order_res = $order->save();

                        // 扣减库存 @todo
                        foreach ($order->detail->toArray() as $dkey=>$dval)
                        {
                            // 修改库存
                            $sku_res = GoodsSkuStock::where('goods_id', $dval['goods_id'])->where('sku_id', $dval['sku_id'])->decrement('quantity', $dval['num']);
                            if ($sku_res)
                            {
                                $goods_res = Goods::where('id', $dval['goods_id'])->decrement('stock_num', $dval['num']);
                            }
                        }

                        // 删除该订单其它未支付的支付单
                        Payment::where('order_bn', $payment->order_bn)->where('status', 'ready')->delete();

                    }
                    Log::info('payment llpay_notify return: Success');
                    // echo 'Success';exit;
                    echo  'Success';exit;
                }
            }

            echo 'Success';exit;
        }
        else
        {
            $msg = '支付失败';
            Log::info('payment llpay_notify request:'. $msg);

            return false;
        }
        // Log::info('payment llpay_notify return: ');
        // exit;

        return false;
    }


    public static function removeBOM($str)
    {
        if (substr($str, 0, 3) === "\xEF\xBB\xBF")
        {
            $str = substr($str, 3);
        }
        return $str;
    }


    /**
     * @api {post} /payment/notify
     * 支付回调
     */
    public function notify(Request $request)
    {
        // $r = PayRecord::paySuccess([]);
        // dd($r);
        Log::info('payment notify-------------------------');

        $request = $request->all();
        Log::info('payment notify request:'. json_encode($request));

        // include '../tools/SignAndCheck.php';
        //$input = file_get_contents("php://input");
        // $input = file_get_contents("php://input", 'r');
        //这个是测试数据。如果异步不通外网可以直接用这个数据测试
        $obj = json_decode($request, TRUE);
        $signature = $obj['sign'];
        $obj['sign'] = '';
        $obj['sign_type'] = '';
        $myfile = fopen("newfile.txt", "w");
        $strData = getStr($obj);

        if(Sumpay::verify($strData, $signature, 'cer/dev_pub.pem'))
        {
            fwrite($myfile, "验证成功\n");
            if($obj['status'] == '00')
            {
                fwrite($myfile, "代付成功");
            }
            else if($obj['status'] == '01')
            {
                fwrite($myfile, "代付处理中");
            }
            else
            {
                fwrite($myfile, "代付失败");
            }

            $arr = array('resp_code'=>'000000');
            echo json_encode($arr);
        }
        else
        {
            fwrite($myfile, "验证失败");
            $arr = array('resp_code'=>'999999');
            echo json_encode($arr);
        }

        exit;
    }

}
